import networkx as nx

metric_map = {
    100014: 'ResponseTime',
    100015: 'ErrorCount',
    100016: 'QueryPerSecond'
}

paths = []


def consAnomalyChain(graph, service_id, metric_id, anomalous_services):
    nodes = graph['nodes']
    edges = graph['edges']
    g = nx.DiGraph()
    g_rev = nx.DiGraph()
    g.add_nodes_from([item['id'] for item in nodes])
    g.add_edges_from([(item['source'], item['target']) for item in edges])
    g_rev.add_nodes_from([item['id'] for item in nodes])
    g_rev.add_edges_from([(item['target'], item['source']) for item in edges])
    services = [item for item in anomalous_services if metric_map[metric_id] in item['anomalous_metrics']]
    if metric_id == 100016:
        for service in services:
            dfs_visit(g, service, services, [])
    else:
        for service in services:
            dfs_visit(g_rev, service, services, [])
    print(paths)
    res = []
    for path in paths:
        if len(path) > len(res):
            res = path.copy()
    for node in res:
        node['subject'] = True if node['id'] == service_id else False

    return res


def dfs_visit(graph, service, services, path):
    if service['id'] not in [i['id'] for i in path] and service['id'] in [i['id'] for i in services]:
        path.append(service)
        adj_nodes = [node for node in services if node['id'] in graph.adj[service['id']]]
        for node in adj_nodes:
            dfs_visit(graph, node, services, path.copy())
    global paths
    paths.append(path.copy())






